import React, { useCallback } from 'react'
import { SchemaForm, Item, Observer, useForm, useObserver, SchemaType } from '@amazebird/antd-schema-form'
import { hex2rgb } from '../linkage/data'

const schema: SchemaType = {
  RGB: {
    type: 'object',
    value: Observer({
      watch: '#rgb',
      filter: (rgb) => !!rgb,
      action: (rgb) => rgb
    }),
    fields: {
      r: {
        label: 'r',
        component: 'InputNumber',
        rules: [
          { max: 255, type: 'number' }
        ],
        required: true
      },
      g: {
        label: 'g',
        component: 'InputNumber',
        required: true,
        rules: [
          { max: 255, type: 'number' }
        ]
      },
      b: {
        label: 'b',
        component: 'InputNumber',
        required: true,
        rules: [
          { max: 255, type: 'number' }
        ]
      }
    }
  }
}

function ColorButton({ hex }) {
  const form = useForm()

  const setColor = useCallback(() => {
    const rgb = hex2rgb(hex)
    form.setState({ rgb })
  }, [])
  const style = {
    width: 80,
    height: 80,
    display: 'flex',
    alignItems: 'center',
    justifyContent: 'center',
    cursor: 'pointer',
    backgroundColor: hex
  }
  return (
    <div onClick={setColor} style={style} >{hex}</div>
  )
}

function ColorBlock() {
  const [rgb] = useObserver(['RGB'])
  const style: React.CSSProperties = {
    width: 120,
    height: 120,
    border: '1px solid #d9d9d9',
    display: 'flex',
    alignItems: 'center',
    justifyContent: 'center'
  }
  let rgbStyle
  if (rgb) {
    const { r, g, b } = rgb
    style.backgroundColor = rgbStyle = `rgb(${r},${g},${b})`
  }
  return (
    <div style={{ display: 'flex', margin: 30 }}>
      <div style={style}>
        {rgbStyle}
      </div>
    </div>
  )
}

function StateDemo() {
  return (
    <SchemaForm schema={schema} initialValues={{ RGB: { r: 25, g: 255, b: 255 } }}>
      <ColorBlock />
      <Item field="RGB">
        <div style={{ display: 'flex' }}>
          <Item field="r" />
          <Item field="g" />
          <Item field="b" />
        </div>
      </Item>
      <div style={{ display: 'flex' }}>
        <ColorButton hex="#DB7093" />
        <ColorButton hex="#AFEEEE" />
        <ColorButton hex="#6495ED" />
      </div>
    </SchemaForm>
  )
}

export default StateDemo
